package org.example.demo.view.webview;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.saxsys.mvvmfx.FxmlView;
import javafx.collections.FXCollections;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.web.WebView;
import org.controlsfx.control.Notifications;
import org.example.demo.entity.MarkPointEntity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * MapView
 *
 * @author ruiqi
 * @date 2024/10/14 15:37
 */
public class MapView implements FxmlView<MapViewModel>, Initializable {

    public ListView<String> institutionList;
    public WebView webview;
    public TextField provinceText;
    public TextField cityText;
    public TextField coordinateXText;
    public TextField coordinateYText;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 创建标记点列表
        List<MarkPointEntity> markPoints = new ArrayList<>();
        markPoints.add(new MarkPointEntity(new double[]{118.984,31.5813}, "{118.984,31.581}"));
        markPoints.add(new MarkPointEntity(new double[]{118.784,32.0813}, "{118.784,32.081}"));

        // 使用 Jackson 将列表转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();

        // 读取 JSON 文件
        Pair<String,String> jsonPair = readJsonByLocation("江苏省","南京市");
        //加载地图webview
        webview.getEngine().load(getClass().getResource("/org/example/demo/html/cnmap.html").toString());
        webview.getEngine().getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == Worker.State.SUCCEEDED) {
                // 在页面加载完成后检查 provinces 和 cityMap 是否已定义
                try {
                    webview.getEngine().executeScript("showMap('江苏省', '南京市', "+
                            objectMapper.writeValueAsString(markPoints)+","+jsonPair.getKey()+","+jsonPair.getValue() +")");
                    webview.getEngine().executeScript("setStyle(false)");
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }



    //根据登录用户省市信息获取对应json文件内容
    private Pair<String,String> readJsonByLocation(String province, String city){
        Pair<String,String> resp = new Pair<>(null,null);
        ObjectMapper objectMapper = new ObjectMapper();
        //读取sheng.json文件
        Map<String, String> provinceMap = null;
        Map<String, String> cityMap = null;
        try {
            // 读取 JSON 文件并转换为 Map
            provinceMap = objectMapper.readValue(new File("./mapJSON/sheng.json"), Map.class);
            cityMap = objectMapper.readValue(new File("./mapJSON/shi.json"), Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(!StrUtil.isBlank(province)&&StrUtil.isBlank(city)){
            //返回省对应json
            if(provinceMap.containsKey(province)){
                String proviceJson = null;
                try (InputStream provinceStream = new FileInputStream("./mapJSON/province/"+provinceMap.get(province)+".json");){
                    proviceJson = readInputStream(provinceStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return new Pair<>(proviceJson,null);
            }
        }else if(!StrUtil.isBlank(province)&&!StrUtil.isBlank(city)){
            if(provinceMap.containsKey(province)&&cityMap.containsKey(city)){
                String cityJson = null;
                try (InputStream citySream = new FileInputStream("./mapJSON/city/"+cityMap.get(city)+".json")) {
                    cityJson = readInputStream(citySream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return new Pair<>(null,cityJson);
            }
        }
        return new Pair<>(null,null);
    }

    private String readInputStream(InputStream inputStream) {
        if (inputStream != null) {
            try {
                return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null; // 返回一个空的 JSON 对象
    }

    public void onSelectBtnAction(ActionEvent actionEvent) {
        // 创建标记点列表
        List<MarkPointEntity> markPoints = new ArrayList<>();
        if(!StrUtil.isBlank(coordinateXText.getText())&&!StrUtil.isBlank(coordinateYText.getText())) {
            markPoints.add(new MarkPointEntity(new double[]{Double.parseDouble(coordinateXText.getText()),
                    Double.parseDouble(coordinateYText.getText())},
                    "{" + coordinateXText.getText() + "," + coordinateYText.getText() + "}"));
        }

        // 使用 Jackson 将列表转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        // 读取 JSON 文件
        Pair<String,String> jsonPair = readJsonByLocation(provinceText.getText(),cityText.getText());
        if(jsonPair.getKey()==null&&jsonPair.getValue()==null){
            Notifications.create().text("未找到当前输入省市地图信息，请检查输入！");
        }
        if(webview.getEngine().getLoadWorker().stateProperty().get().equals(Worker.State.SUCCEEDED)){
            try {
                webview.getEngine().executeScript("showMap('"+provinceText.getText()+"', '"+cityText.getText()+"', "+
                        objectMapper.writeValueAsString(markPoints)+","+jsonPair.getKey()+","+jsonPair.getValue() +")");
                webview.getEngine().executeScript("setStyle(false)");
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

